﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _List转DataTable
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Person> persons = new List<Person>() {
                new Person() { Id=1, Name="张三", Sex="男", Birthday=DateTime.Now.AddYears(-19), InputTime=DateTime.Now },
                new Person() { Id=2, Name="小红", Sex="女", Birthday=DateTime.Now.AddYears(-20), InputTime=DateTime.Now }
            };

            GetDataTable<Person>(persons);

            Console.ReadKey();
        }

        public static DataTable GetDataTable<T>(List<T> entitys)
        {

            DataTable dt = new DataTable("PersonList");
            if (entitys.Count > 0)
            {
                PropertyInfo[] info = entitys[0].GetType().GetProperties();
                ///添加 表头
                for (int i = 0; i < info.Length; i++)
                {
                    dt.Columns.Add(info[i].Name, info[i].PropertyType);
                }
                //foreach (PropertyInfo p in info)
                //{
                //    dt.Columns.Add(p.Name, p.PropertyType);
                //}

                ///循环创建行 并充填数据
                foreach (T entity in entitys)
                {
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < info.Length; i++)
                    {
                        dr[info[i].Name] = info[i].GetValue(entity, null);
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

    }
}
